// let urlEnv = require("@/config/env");
import instance from "@/main";
import initSocket from "@/util/socket";

const socketFuture = {
  state: {
    futureWs: null,
    futureWsReadyState: null,
    futureLockReconnect: false, // 连接锁，避免重复连接
    futureTimeoutSet: null, // 延时器
    futureTimeout: 3000, // 超时重连间隔
    futureReconnectNum: 1, // 重连次数
    futureHeartbeatInterval: null,
    futureData: {} // 行情数据
  },
  mutations: {
    RESET_FUTURE_RECONNECT_NUM: state => {
      state.futureReconnectNum = 1;
    },
    CLOSE_FUTURE_WS: state => {
      if (state.futureWs) state.futureWs.close();
      state = {
        futureWs: null,
        futureWsReadyState: null,
        futureLockReconnect: false, // 连接锁，避免重复连接
        futureTimeoutSet: null, // 延时器
        futureTimeout: 3000, // 超时重连间隔
        futureReconnectNum: 1, // 重连次数
        futureHeartbeatInterval: null,
        futureData: {} // 行情数据
      };
      clearInterval(state.futureHeartbeatInterval);
    },
    // 更新行情数据
    UPDATE_FUTURE_DATA: (state, data) => {
      instance.$set(state.futureData, data.key, data.val);
    }
  },
  actions: {
    // 心跳
    futureHeartbeat: ({ state }) => {
      state.futureHeartbeatInterval = setInterval(() => {
        state.futureWs.send("futureHeartbeat");
      }, 60000 * 30);
    },
    // 重置重连次数
    resetFutureReconnectNum: ({ commit }) => {
      commit("RESET_FUTURE_RECONNECT_NUM");
    },
    // 重新连接
    reconnectFutureWs: ({ state, dispatch }) => {
      if (state.futureLockReconnect) return;
      console.log("futureWs准备重连");
      state.futureLockReconnect = true;
      // 重连最大次数3次
      if (state.futureReconnectNum <= 3) {
        state.futureWsReadyState = 0;
        state.futureTimeoutSet = setTimeout(() => {
          console.log(`futureWs正在重连，第${state.futureReconnectNum}次`);
          dispatch("createfutureWs");
          state.futureReconnectNum++;
          state.futureLockReconnect = false;
        }, state.futureTimeout); // 延迟3秒重连
      } else {
        console.log(`重连次数已超3次`);
        state.futureWsReadyState = null;
        state.futureLockReconnect = false;
        // // 重连超过3次后退出登录
        // dispatch("logout").then(() => {
        //   instance.$router.push({
        //     name: "home"
        //   });
        // });
      }
    },
    // 创建行情socket
    createfutureWs: ({ state, commit, dispatch }) => {
      return new Promise(resolve => {
        state.futureWs = new initSocket("md/subscribe");
        console.log(state.futureWs);
        state.futureWsReadyState = 0;
        state.futureWs.onopen = () => {
          resolve();
          console.log("futureWs.onopen");
          // 开启心跳
          dispatch("futureHeartbeat");
          state.futureWsReadyState = 1;
          state.futureWs.onerror = err => {
            console.log("futureWs.onerror", err);
          };
        };
        // 接收行情数据
        state.futureWs.onmessage = res => {
          let data = JSON.parse(res.data);
          // 更新行情数据
          commit("UPDATE_FUTURE_DATA", {
            key: data.instrumentId.toLowerCase(),
            val: data
          });
        };
        state.futureWs.onclose = data => {
          // 清除定时器
          clearInterval(state.futureHeartbeatInterval);
          state.futureHeartbeatInterval = null;
          // code 4001 代表被踢下线; 1000 代表主动关闭
          if (data.code !== 1000) {
            state.futureWsReadyState = null;
            // } else {
            // 异常关闭时进行重连
            dispatch("reconnectFutureWs");
          }
        };
      });
    },
    // 发送参数
    futureWsSend: ({ state, commit }, data) => {
      // ws是否处于连接状态
      if (state.futureWsReadyState === 1) {
        // 将订阅的合约月存储起来，合约名为key
        data.forEach(item => {
          commit("UPDATE_FUTURE_DATA", {
            key: item.toLowerCase(),
            val: {}
          });
        });
        let params = JSON.stringify({
          subscribeList: data
        });
        state.futureWs.send(params);
      }
    },
    // 关闭行情ws
    closefutureWs: ({ commit }) => {
      commit("CLOSE_FUTURE_WS");
    }
  }
};

export default socketFuture;
